<template>
  <div class="tpl-container">
    <div class="mb20 condition-container">
      <div class="condition">
        <span class="color_494949 ft12 pr5">{{ translate('物料编码') }}：</span>
        <ElInput
          v-model="itemcode"
          class="w164 mr14"
          :placeholder="translate('请输入物料名称')"
        />
      </div>
      <div class="condition">
        <span class="color_494949 ft12 pr5">{{ translate('库位') }}：</span>
        <ElInput
          v-model="itemCate"
          class="w164 mr14"
          :placeholder="translate('请输入库位名称')"
        />
      </div>
      <div class="condition">
        <span class="color_494949 ft12 pr5">{{ translate('单位') }}：</span>
        <el-autocomplete
          v-model="whUnit"
          class="inline-input mr10"
          :fetch-suggestions="querySearch"
          placeholder="选择单位"
          @select="handleSelect"
        />
      </div>
      <div class="condition">
        <span class="color_494949 ft12 pr5">{{ translate('标识') }}：</span>
        <el-select
          v-model="Sign"
          class="w164"
          :placeholder="translate('请选择')"
        >
          <el-option
            v-for="item in OptionReceive"
            :key="item.value"
            :label="item.lable"
            :value="item.value"
          />
        </el-select>
      </div>
      <div class="condition">
        <span class="color_494949 ft12 pr5">{{ translate('备注') }}：</span>
        <ElInput
          v-model="remark"
          class="w164 mr14"
          :placeholder="translate('请输入备注内容')"
        />
      </div>
      <div class="condition">
        <span class="w70 color_494949 ft12 pr5">{{ translate('时间') }}：</span>
        <el-date-picker
          v-model="dateTime"
          end-placeholder="结束日期"
          range-separator="至"
          start-placeholder="开始日期"
          type="daterange"
          value-format="YYYY-MM-DD"
        />
      </div>
      <div class="condition">
        <ElButton class="settingBtn" type="primary" @click="search">
          {{ translate('查询') }}
        </ElButton>
      </div>
    </div>
    <div class="add">
        <el-button
          class="settingBtn"
          type="primary"
          @click="download"
          plain
        >
          {{ translate('导出') }}
        </el-button>
    </div>
    <div class="table">
      <ElTable
        ref="multipleTableRef"
        v-loading="loading"
        :border="true"
        :data="tableData"
      >
      <ElTableColumn
          :label="translate('发料单位')"
          prop="WHUnit"
          width="auto"
        />
        <ElTableColumn :label="translate('库位')" prop="WSCode" width="auto" />
        <ElTableColumn
          :label="translate('大类')"
          prop="ItemCate"
          width="auto"
        />
        <ElTableColumn :label="translate('物料编码')" width="200">
          <template #default="{ row }">
            <div>
              <span class="iconcolor">{{ row.ItemCode }}</span>
              <vab-icon icon="file-copy-line" @click="copyToClipboard(row.ItemCode)" />
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn
          :label="translate('物料名称')"
          prop="ItemName"
          width="auto"
        />
        <ElTableColumn
          :label="translate('物料规格')"
          prop="ItemSpec"
          width="auto"
        />
        <ElTableColumn
          :label="translate('物资单位')"
          prop="ItemUnit"
          width="60"
        />
        <ElTableColumn :label="translate('标识')" prop="Sign" width="60" />
        <ElTableColumn
          :label="translate('库存数量')"
          prop="StockQty"
          width="auto"
        />
        <ElTableColumn :label="translate('数量')" width="auto">
          <template #default="{ row }">
            <div>
              <span class="color_red">{{ row.Qty }}</span>
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn :label="translate('单价')" prop="Price" width="auto" />
        <ElTableColumn :label="translate('金额')" prop="Amt" width="auto" />
      </ElTable>
      <div v-if="total > 0" class="pagination">
        <ElPagination
          background
          :current-page="searchInfo.pageNo"
          :layout="layout"
          :page-size="searchInfo.pageSize"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref } from 'vue'
  import { GetPageDataInOutItemReport, ExportInOutItemReport } from '@/api/mupro'
  import { BaseGetPageData } from '@/api/item'
  import { MenuAuth } from '~/src/utils/permission'
  import { useUserStore } from '@/store/modules/user'
  import { translate } from '@/i18n'
  import { baseURL } from '@/config'
  import { parseTime } from '@/utils'
  const { token } = useUserStore()
  const itemname = ref('')
  const itemcode = ref('')
  const itemCate = ref('')
  const whUnit = ref('')
  const billNo = ref('')
  const storageLocation = ref('')
  const PayLoadTopic = ref('')
  const date = ref('')
  const remark = ref('')
  const OptionReceive = ref([
    {
      lable: '全部',
      value: '全部',
    },
    {
      lable: '出库(-)',
      value: '出库(-)',
    },
    {
      lable: '入库(+)',
      value: '入库(+)',
    },
  ])
  const Sign = ref('')
  const searchInfo = reactive({
    pageNo: 1,
    pageSize: 10,
    tableName: '',
    sort: '',
    order: '',
    wheres: `[{"name":"ItemCode","value":${itemcode.value},"displayType":"like"},
              {"name":"WSCode","value":${itemCate.value},"displayType":"like"},
              {"name":"WHUnit","value":${whUnit.value},"displayType":"like"},
              {"name":"Remark","value":${remark.value},"displayType":"like"}]`,
    export: false,
    value: '',
  })
  const getLastDayOfMonth = ()=> {
      // 创建一个当前日期的副本
          let date = new Date();

          // 设置日期为下个月的第一天（这样可以跳过本月所有日期）
          date.setDate(1);
          date.setMonth(date.getMonth() + 1);
          date.setDate(0); // 这会将日期设置为上一个月的最后一天

          // 格式化日期为 YYYY-MM-DD
          let year = date.getFullYear();
          let month = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的，所以要加1
          let day = String(date.getDate()).padStart(2, '0');

          return `${year}-${month}-${day}`;
      }
     const getFirstDayOfMonthFormatted = () => {
            const today = new Date(); // 获取当前日期
            const year = today.getFullYear(); // 获取年份
            const month = today.getMonth(); // 获取月份（注意：0表示1月，11表示12月）
            const date = 1; // 设置日期为1（即当前月份的第一天）

            // 创建日期对象
            const firstDay = new Date(year, month, date);

            // 手动格式化日期为 YYYY-MM-DD
            const formattedDate = `${year.toString().padStart(4, '0')}-${(month + 1).toString().padStart(2, '0')}-${date.toString().padStart(2, '0')}`;
            return formattedDate;
        }
  const dateTime = ref([getFirstDayOfMonthFormatted(),getLastDayOfMonth()])
  searchInfo.wheres =  `[{"name":"ItemCode","value":${itemcode.value},"displayType":"like"},
              {"name":"WSCode","value":${itemCate.value},"displayType":"like"},
              {"name":"WHUnit","value":${whUnit.value},"displayType":"like"},
              {"name":"CreateDate","value":${dateTime.value[0]},"displayType":"ThanOrEqual"},
              {"name":"CreateDate","value":${dateTime.value[1]},"displayType":"LessOrequal"},
              {"name":"Remark","value":${remark.value},"displayType":"like"}]`
  const loading = ref(false)
  const action = ref('')
  const layout = ref('total, sizes, prev, pager, next, jumper')
  const tableData = ref([])
  const total = ref(0)
  const listLoading = ref(false)
  const headers = ref('')
  const WHdata = ref([])
  // 获取表格数据
  const gettableData = async () => {
    loading.value = true
    const { data } = await GetPageDataInOutItemReport(searchInfo)
    loading.value = false
    tableData.value = data?.rows || []
    total.value = data?.total || 0
  }
  gettableData()
  //分页条数切换
  const handleSizeChange = (val: any) => {
    searchInfo.pageSize = val
    gettableData()
  }
  //分页切换
  const handleCurrentChange = (val: any) => {
    searchInfo.pageNo = val
    gettableData()
  }
  const handleSelect = (item) => {
    console.log(item)
  }
  // 物资出入库导出
  const download = async () => {
    const data = await ExportInOutItemReport(searchInfo)
    if (data) {
      console.log(data)
      const blob = new Blob([data])
      const url = URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.download = `物资出入库汇总.xlsx`
      link.href = url
      link.click()
    }
  }
  const querySearch = (queryString, cb) => {
    const restaurants = WHdata.value
    const results =
      queryString && queryString != 'null'
        ? restaurants.filter(createFilter(queryString))
        : restaurants
    console.log(results)
    // 调用 callback 返回建议列表的数据
    cb(results)
  }
  const createFilter = (queryString) => {
    return (restaurant) => {
      console.log(restaurant)
      return (
        restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
      )
    }
  }
  const WHGetPageData1 = async () => {
    const params = {
      pageNo: 1,
      pageSize: 10,
      wheres: `[{"name":"ModuleId","value":"","displayType":"equal"}]`,
      export: true,
      moduleType: 'ModuleId',
      sort: 'SortCode',
      order: 'ASC',
      search: '',
    }
    const data = await BaseGetPageData(params)
    if (data.data.rows && data.data.rows.length > 0) {
      data.data.rows.map((item) => {
        item.value = item.FullName
      })
    }
    WHdata.value = data.data.rows
  }
  WHGetPageData1()
   //复制标识
 const copyToClipboard =async (val: any) => {
    if (navigator.clipboard && window.isSecureContext) {
      try {
      console.log(navigator.clipboard)
      console.log(window.isSecureContext)
      await navigator.clipboard.writeText(val)
      ElMessage({
        message:'复制成功',
        type:'success',
      })
      } catch (err) {
        ElMessage({
        message:'复制失败',
        type:'error',
      })
      }

      }else {
        // 创建text area
      const textArea = document.createElement("textarea")
      textArea.value = val
      // 使text area不在viewport，同时设置不可见
      textArea.style.position = "absolute"
      textArea.style.opacity = 0
      textArea.style.left = "-999999px"
      textArea.style.top = "-999999px"
      document.body.appendChild(textArea)
      textArea.focus()
      textArea.select()

      return new Promise((res, rej) => {
        // 执行复制命令并移除文本框
        document.execCommand("copy") ? res() : rej()
        textArea.remove()
      }).then(() => {
          ElMessage({
            message: "复制成功",
            type: "success",
          })
        }).catch((err) => {
          ElMessage({
            message: "复制失败",
            type: "error",
          })
        })
      }

  }
  const search = () => {
    searchInfo.pageNo = 1
    if (
      itemcode.value.trim() !== '' ||
      Sign.value.trim() !== '' ||
      itemCate.value.trim() !== '' ||
      whUnit.value.trim() !== '' ||
      (dateTime.value && dateTime.value[0].trim() !== '')
    ) {
      const arr = []
      itemCate.value.trim() !== '' &&
        arr.push({
          name: 'WSCode',
          value: itemCate.value,
          displayType: 'like',
        })
        remark.value.trim() !== '' &&
        arr.push({
          name: 'Remark',
          value: remark.value,
          displayType: 'like',
        })
        whUnit.value.trim() !== '' &&
        arr.push({
          name: 'WHUnit',
          value: whUnit.value,
          displayType: 'like',
        })
      itemcode.value.trim() !== '' &&
        arr.push({
          name: 'ItemCode',
          value: itemcode.value,
          displayType: 'like',
        })
      dateTime.value &&
        dateTime.value[0].trim() !== '' &&
        arr.push({
          name: 'CreateDate',
          value: dateTime.value[0],
          displayType: 'ThanOrEqual',
        })
      dateTime.value &&
        dateTime.value[1].trim() !== '' &&
        arr.push({
          name: 'CreateDate',
          value: dateTime.value[1],
          displayType: 'LessOrequal',
        })
      searchInfo.value = Sign.value === '入库(+)' ? '+': Sign.value === '出库(-)'? '-': '',
      searchInfo.wheres = JSON.stringify(arr)
    } else {
      searchInfo.value = ''
      searchInfo.wheres = `[{"name":"ItemCode","value": '',"displayType":"like"}]`
    }
    // searchInfo.date = date.value
    gettableData()
  }
</script>

<style lang="scss" scoped>
  .tpl-container {
    .color_494949 {
      color: #494949;
    }

    .noData {
      text-align: center;
      font-size: 16px;
      color: gray;
    }
    .w164 {
      width: 164px !important;
    }
    .inline-input {
      width: 164px !important;
    }
    .mb20 {
      margin-bottom: 20px;
    }

    .img-container {
      display: flex;
      // justify-content: center;

      .img {
        width: 100px;
      }
    }
    .w70 {
      display: inline-block;
      width: 70px;
      text-align: right;
    }

    .condition-container {
      display: flex;
      flex-wrap: wrap;
      align-items: center;

      .condition {
        margin-right: 14px;
        margin-bottom: 10px;
      }
    }
  }
  .el-table {
    & ::v-deep th.el-table__cell,
    ::v-deep td.el-table__cell {
      // 设置position 使得 子元素不与其产生新的层叠关系
      position: static;
    }
  }
  ::v-deep .el-autocomplete {
    width: 164px;
  }
  .ml-upload {
    display: inline-block;
    margin-left: 10px;
    vertical-align: bottom;
    margin-right: 10px;
  }
  .add {
      margin-bottom: 10px;
      text-align: left;
    }
  .iconcolor {
      color: #409eff;
    }
  .color_red {
      color: #f56c6c;
    }
</style>
